<template>
  <div class="content">
    <el-button
      type="primary"
      icon="el-icon-plus
"
      @click="addBrand()"
      >添加</el-button
    >
    <div class="table">
      <el-table :data="currentBrandList" style="width: 100%" border>
        <el-table-column label="序号" width="180" type="index" align="center">
        </el-table-column>
        <el-table-column
          label="品牌名字"
          width="180"
          prop="tmName"
          align="center"
        >
        </el-table-column>
        <el-table-column label="品牌LOGO" align="center">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.logoUrl"
              align="center"
              fit="fill"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="warning"
              icon="el-icon-edit"
              @click="handleEdit(scope.$index, scope.row)"
              >修改</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination
        align="center"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="limit"
        :page-sizes="[defaultLimit, 5, 10, 15, 20]"
        layout=" prev, pager, next, jumper,->, total,sizes"
        :total="allBrandList.length"
      >
      </el-pagination>
    </div>
    <div>
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form
          label-width="180px"
          :model="fromBrand"
          :rules="rules"
          ref="fromBrand"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="fromBrand.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/list-api/admin/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="fromBrand.logoUrl"
                :src="fromBrand.logoUrl"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addOrUpdateBrand()"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </div>
  </div>
</template>
  </div>
</template>

<script>
export default {
  name: "Brand",

  data() {
    return {
      allBrandList: [],
      limit: 3, //每页显示的条数
      defaultLimit: 3, // 默认显示条数
      currentPage: 1, //当前页
      currentBrandList: [{ id: 1, logoUrl: "", tnName: "" }], //当前页品牌
      dialogVisible: false, //是否显示el-dialog
      dialogTitle: "", //el-dialog标题
      fromBrand: {
        id: -1, // -1标识无id，用于添加品牌
        tmName: null,
        logoUrl: "",
      },
      //品牌表单验证
      rules: {
        tmName: [
          { required: true, message: "请输入品牌名称" },
          { min: 1, max: 6, message: "长度在 1 到 6 个字符", trigger: "blur" },
        ],
        logoUrl: [{ required: true, message: "请上传图片" }],
      },
    };
  },
  mounted() {
    this.getAllBrandList();
    this.getBrandList();
  },
  methods: {
    //获取品牌列表总数
    async getAllBrandList() {
      let res = await this.$api.brand.getAllBrandList();
      this.allBrandList = res.data;
    },
    //获取当前分页品牌
    async getBrandList() {
      let res = await this.$api.brand.getBrandList(
        this.currentPage,
        this.limit
      );
      //当前页
      this.currentPage = res.data.current;
      // 品牌数据
      this.currentBrandList = res.data.records;
    },
    //添加品牌
    addBrand() {
      this.dialogTitle = "添加品牌";
      // 显示el-dialog
      this.dialogVisible = true;
      //清空数据
      this.fromBrand.logoUrl = "";
      this.fromBrand.tmName = "";
      this.fromBrand.id = -1;
    },
    //修改品牌
    handleEdit(index, row) {
      this.dialogTitle = "修改品牌";
      // 显示el-dialog
      this.dialogVisible = true;
      // 获取修改品牌信息
      Object.assign(this.fromBrand, row);
    },
    //删除品牌
    handleDelete(index, row) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$api.brand.deleteBrand(row.id);
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message({
              type: "info",
              message: "删除失败",
            });
          }
          //刷新列表
          this.getAllBrandList();
          //判断页数是否够显示
          if (this.allBrandList.length % this.limit === 1) {
            this.currentPage--;
          }
          this.getBrandList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange(val) {
      //改变当前页
      this.currentPage = val;
      this.getBrandList();
    },
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.limit = val;
      this.getBrandList();
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 上传图片成功
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.fromBrand.logoUrl = res.data;
      } else {
        this.$message({
          type: "info",
          message: "上传失败",
        });
      }
    },
    //图片上传前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt500KB = file.size / 500 / 1024 < 1;
      if (!isJPG) {
        if (!isPNG) {
          this.$message.error("上传头像图片只能是 JPG或PNG 格式!");
        }
      }
      if (!isLt500KB) {
        this.$message.error("上传头像图片大小不能超过 500KB!");
      }
      if (isJPG | isPNG) {
        if (isLt500KB) {
          return true;
        }
      }
    },
    //添加或修改品牌
    async addOrUpdateBrand() {
      // 表单验证
      this.$refs.fromBrand.validate(async (valid) => {
        // 表单验证通过
        if (valid) {
          //有id为修改，没有id为添加
          if (this.fromBrand.id !== -1) {
            console.log(t);
            let res = await this.$api.brand.updateBrand(this.fromBrand.id);
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "品牌修改成功!",
              });
              this.dialogVisible = false;
              //刷新列表
              this.getAllBrandList();
              this.getBrandList();
            }
          } else {
            //整理数据去掉id，给后端添加id
            let brand = {
              tmName: this.fromBrand.tmName,
              logoUrl: this.fromBrand.logoUrl,
            };
            let t = {
              tmName: "111",
              logoUrl: "http://139.198.127.41:9000/sph/20240326/1.jpg",
            };
            let res = await this.$api.brand.addBrand(t);
            if (res.code === 200) {
              this.$message({
                type: "success",
                message: "品牌添加成功!",
              });
              this.dialogVisible = false;
              //刷新列表
              this.getAllBrandList();
              this.getBrandList();
            }
          }
        }
      });
    },
  },
};
</script>

<style  scoped>
.content {
  margin: 20px;
}
.table {
  margin-top: 20px;
}
.block {
  margin-top: 20px;
}
.el-upload__tip {
  color: red;
}
</style>